package com.hmtech.aup.presentation.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hmtech.aup.R
import com.hmtech.aup.databinding.FragmentHomeBinding
import kotlinx.coroutines.launch

class HomeFragment : Fragment() {
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    // 引入 ViewModel
    private val categoryViewModel: CategoryViewModel by viewModels()

    // RecyclerView Adapter（假设你已经有了 CategoryAdapter）
    private lateinit var adapter: CategoryAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewAsync(view)
    }

    private fun initViewAsync(rootView: View) {
        lifecycleScope.launch { // 延迟这么多时间
            doInitViews(rootView)
        }
    }

    private fun doInitViews(root: View) {
        // 初始化CategoryAdapter
        adapter = CategoryAdapter()
        val rv = root.findViewById<RecyclerView>(R.id.rvCategory)
        rv.layoutManager = LinearLayoutManager(requireContext())
        rv.adapter = adapter

        // 2. 观察 ViewModel 的 LiveData
        categoryViewModel.categoriesResp.observe(viewLifecycleOwner) { resp ->
            adapter.submitList(resp.data)
        }

        // 3. 触发数据加载
        // ✅ 只在数据还没加载过时才触发加载
        if (categoryViewModel.categoriesResp.value == null) {
            categoryViewModel.loadAllWithStyles()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}